package com.ishowcode.controller.SecKillController;
import com.ishowcode.annotation.GlobalInterceptor;
import com.ishowcode.entity.Result;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
public class SecKillController {
    @Resource
    RedisTemplate<String,Object> redisTemplate;
    @RequestMapping("/seckill")
    @GlobalInterceptor(checkLogin = true)
    public synchronized Result SecKill(@RequestParam("email") String email,@RequestParam("username") String username) throws ParseException {
        Object total = redisTemplate.opsForValue().get("SecKill_total");
        Object SecKillTime = redisTemplate.opsForValue().get("SecKill_Time");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date begintime = sdf.parse(SecKillTime.toString());
        Date date = new Date();
        Date now = sdf.parse(sdf.format(date));
        if(begintime.after(now)) return Result.failure("秒杀未开始");
        if ((int)total <= 0) return Result.failure("已经被抢光了,秒杀结束");
        if (redisTemplate.opsForSet().isMember("SecKill_UserID",username))return Result.failure("每人限购一份哦!");
        // 开启事务
        redisTemplate.setEnableTransactionSupport(true);
        List<Object> results = (List<Object>) redisTemplate.execute(new SessionCallback<List<Object>>() {
            @Override
            public List<Object> execute(RedisOperations operations) throws DataAccessException {
                operations.watch("SecKill_total");
                Integer total =(Integer) redisTemplate.opsForValue().get("SecKill_total");
                operations.multi();
                total = total -1;
                if (total < 0) {
                    return null;
                }
                operations.opsForValue().decrement("SecKill_total");
                operations.opsForSet().add("SecKill_UserID",username);
                return operations.exec();
            }
        });

        if (results == null && results.size() < 0) {
            return Result.failure("抢购失败");
        }

        return Result.success("抢购成功");
    }
    @RequestMapping("/seckilltest")
    public  Result seckilltest() throws ParseException {
        Object total = redisTemplate.opsForValue().get("SecKill_total");
        Object SecKillTime = redisTemplate.opsForValue().get("SecKill_Time");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date begintime = sdf.parse(SecKillTime.toString());
        Date date = new Date();
        Date now = sdf.parse(sdf.format(date));
        if(begintime.after(now)) return Result.failure("秒杀未开始");
        if ((int)total <= 0) return Result.failure("已经被抢光了,秒杀结束");
        String username = UUID.randomUUID().toString().substring(0,6);
        if (redisTemplate.opsForSet().isMember("SecKill_UserID",username))return Result.failure("每人限购一份哦!");
        // 开启事务
        redisTemplate.setEnableTransactionSupport(true);
        List<Object> results = (List<Object>) redisTemplate.execute(new SessionCallback<List<Object>>() {
            @Override
            public List<Object> execute(RedisOperations operations) throws DataAccessException {
                operations.watch("SecKill_total");
                Integer total =(Integer) redisTemplate.opsForValue().get("SecKill_total");
                operations.multi();
                total = total -1;
                if (total < 0) {
                    return null;
                }
                operations.opsForValue().decrement("SecKill_total");
                operations.opsForSet().add("SecKill_UserID",username);
                return operations.exec();
            }
        });

        if (results == null && results.size() < 0) {
            return Result.failure("抢购失败");
        }

        return Result.success("抢购成功");
    }
//    @RequestMapping("/seckilltest")
//    public synchronized Result seckilltest() throws ParseException {
//        Object total = redisTemplate.opsForValue().get("SecKill_total");
//        Object SecKillTime = redisTemplate.opsForValue().get("SecKill_Time");
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        Date begintime = sdf.parse(SecKillTime.toString());
//        Date date = new Date();
//        Date now = sdf.parse(sdf.format(date));
//        if(begintime.after(now)) return Result.failure("秒杀未开始");
//        if ((int)total <= 0) return Result.failure("已经被抢光了,秒杀结束");
//        String username = UUID.randomUUID().toString().substring(0,6);
//        if (redisTemplate.opsForSet().isMember("SecKill_UserID",username))return Result.failure("每人限购一份哦!");
//        List<Object> exec = (List<Object>) redisTemplate.execute(new SessionCallback<List<Object>>() {
//            public List<Object> execute(RedisOperations operations) throws DataAccessException {
//                operations.watch("SecKill_total");
//                operations.multi();
//                operations.opsForValue().decrement("SecKill_total");
//                operations.opsForSet().add("SecKill_UserID",username);
//                return operations.exec();
//            }
//        });
//        if (exec==null||exec.size()==0){
//            return Result.failure("抢购失败");
//        }
//        return Result.success("抢购成功");
//    }
    @RequestMapping("/setSecKillInfo")
    @GlobalInterceptor(checkParam = true,checkAdmin = true)
    public Result setSecKillInfo(@RequestParam("email")  String email,@RequestParam("total") Integer total,@RequestParam("seckilltime") String seckilltime){
        if(redisTemplate.opsForSet().members("SecKill_UserID").size()>0){
            Boolean del = redisTemplate.delete("SecKill_UserID");
            if (!del) return Result.failure("设置失败");
        }
        redisTemplate.opsForValue().set("SecKill_total",total);
        redisTemplate.opsForValue().set("SecKill_Time",seckilltime);
            return Result.success();
    }
    @RequestMapping("/getKillInfo")
    @GlobalInterceptor(checkLogin = true,checkParam = true)
    public Result getKillInfo(@RequestParam("email")  String email){
        Object total = redisTemplate.opsForValue().get("SecKill_total");
        Object SecKillTime = redisTemplate.opsForValue().get("SecKill_Time");
        Set<Object> userID = redisTemplate.opsForSet().members("SecKill_UserID");
        Map<String, Object> killInfo = new HashMap<>();
        killInfo.put("total",total);
        killInfo.put("SecKillTime",SecKillTime);
        killInfo.put("seckillusers",userID);
        return Result.success(killInfo);
    }
}
